package com.mgblog.web.action;

import java.util.Date;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.apache.struts2.ServletActionContext;
import org.springframework.stereotype.Controller;

import com.mgblog.service.inter.ArticleServiceInter;
import com.mgblog.service.inter.ArticleSortServiceInter;
import com.mgblog.utils.Tools;
import com.mgblog.vo.Article;
import com.mgblog.vo.ArticleSort;
import com.mgblog.vo.User;
import com.opensymphony.xwork2.ActionContext;

@Controller
public class ArticleAction {
	@Resource
	private ArticleSortServiceInter articleSortService;
	@Resource
	private ArticleServiceInter articleService;
	/**
	 * 到写文章的界面
	 * @return
	 */
	public String toWriteArticleUI(){
		//将文章分类查出来封装好
		List<ArticleSort> asList = articleSortService.getAllArticleSorts("id asc");
		ActionContext.getContext().put("asList", asList);
		return "writeArticleUI";
	}
	/**
	 * 添加文章
	 * @return
	 */
	public String addArticle(){
		Article a = doForm(ServletActionContext.getRequest());
		System.out.println("title:"+a.getTitle()+"\n content:"+a.getContent()+"\n sortId:"+a.getSortId());
		a.setAddTime(new Date());
		a.setArticleSort(articleSortService.getArticleSortById(a.getSortId()));
		a.setUser((User) ActionContext.getContext().getSession().get(Tools.LOGIN_USER));
		//添加
		articleService.addArticle(a);
		return "index";
	}
	/**
	 * 表单封装，自定义
	 * @param r
	 * @return
	 */
	private Article doForm(HttpServletRequest r){
		Article a = new Article();
		if(null != r.getParameter("title"))
			a.setTitle(r.getParameter("title"));
		if(null != r.getParameter("content"))
			a.setContent(r.getParameter("content"));
		if(null != r.getParameter("sortId"))
			a.setSortId(Integer.parseInt(r.getParameter("sortId").trim()));
		
		return a;
			
			
	}
}
